//
//  Templet2ViewController.m
//  FruitsWholesaler
//
//  Created by sgone-2 on 16/4/7.
//  Copyright © 2016年 sgone. All rights reserved.
//

#import "Templet2ViewController.h"
#import "AFNetworking.h"
#import "DetailMoBanViewController.h"
#import "MBProgressHUD+MJ.h"

@interface Templet2ViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>



@property(nonatomic,strong) UICollectionView *collectionView;

@property (weak, nonatomic) IBOutlet UIButton *btnDaoru;



//设定bool标示
@property(strong,nonatomic) NSMutableArray* boolArray;
//重新获得新的数组,里面判断勾选的状态
@property(nonatomic,strong) NSMutableArray *dataArray;
//网路请求
@property(nonatomic,strong)AFHTTPSessionManager *manager;
//取得全部数据
@property(nonatomic,strong) NSMutableArray *list;




@end

@implementation Templet2ViewController


//隐藏tabbar
-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.hidesBottomBarWhenPushed = YES;
        
    }
    return self;
}




//afnetworking网络请求数据
- (AFHTTPSessionManager *)manager
{
    if (_manager == nil) {
        _manager  = [AFHTTPSessionManager manager];
    }
    return _manager;
    
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.titleLabel.text = @"模板导入";
    self.backBtn.hidden = NO;
    
    [self creatUI];
    [self sendAPI];
    
}

-(void)creatUI
{

    
    
    
    
    UICollectionViewFlowLayout *flowLayout=[[UICollectionViewFlowLayout alloc] init];
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 64, ViewWidth, ViewHeight - 64 -60) collectionViewLayout:flowLayout];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    //注册collectionCell
    [self.collectionView registerNib:[UINib nibWithNibName:@"Templet2Cell" bundle:nil] forCellWithReuseIdentifier:@"Templet2Cell"];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:self.collectionView];
    self.collectionView.backgroundColor = BACKGROUND1;
    
    
    
    self.rightBut.hidden = NO;
    self.rightBut.frame = CGRectMake(ViewWidth *0.78, 20, 74, 44);
    self.rightBut.titleLabel.font = [UIFont systemFontOfSize:15/FDLaOt];
    [self.rightBut setTitle:@"全选" forState:UIControlStateNormal];
    self.btnDaoru.backgroundColor = BenSe_COLOR;
    self.btnDaoru.tintColor = [UIColor whiteColor];
    [self.btnDaoru setTitle:@"一  键  导  入" forState:UIControlStateNormal];
    [self.btnDaoru addTarget:self action:@selector(daoRu:) forControlEvents:UIControlEventTouchUpInside];

    
    

}

#pragma mark 全部选择

-(void)rightButClick:(UIButton *)sender
{

    
    if (!sender.tag) {
        
        [sender setTitle:@"取消" forState:UIControlStateNormal];
        for (int i = 0 ; i < self.boolArray.count; i++) {
            
            
            [self.boolArray replaceObjectAtIndex:i withObject:@"YES"];
        }
        [self.collectionView reloadData];
        sender.tag = 1;
        
    }
    else
    {
        
        [sender setTitle:@"全选" forState:UIControlStateNormal];
        for (int i = 0; i < self.boolArray.count; i++) {
            
            [self.boolArray replaceObjectAtIndex:i withObject:@"NO"];
            
        }
        
        [self.collectionView reloadData];
        sender.tag = 0 ;
        
        
    }



}



#pragma mark 导入全部数据
-(void)daoRu:(UIButton *)sender
{


    NSString *goodsID = @"";
    //将数据进行导入
    for (int i = 0; i < self.boolArray.count; i++) {
      
        NSString *boolStr = self.boolArray[i];
        
        if ([boolStr isEqualToString:@"YES"]) {
            NSDictionary *dic = [self.list objectAtIndex:i];
            
            NSString *ID = [dic valueForKey:@"product_id"];
            if (!i) {
                
                goodsID = [NSString stringWithFormat:@"%@",ID];
                
            }
            else
            {
             
                goodsID =[NSString stringWithFormat:@"%@,%@",goodsID,ID];
            
            }
            
        }
    
    }
    
    if (goodsID.length == 0) {
        
        [self.view makeToast:@"请选择商品"];
        return;
        
        
    }
    
    
    NSString *urlStr = [NSString stringWithFormat:@"%@import_product_template",SERVER_ADDRESS2];
    
    NSDictionary *params =@{@"wTel" : self.dataHandler.phone , @"uToken" : self.dataHandler.uToken , @"product_id" : goodsID}
    ;
    
    [MBProgressHUD showHUDAddedTo:self.collectionView animated:YES];

    [self.manager POST:urlStr parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
        
        
        if ([responseObject[@"error_flag"]intValue] == 0) {
            
            [MBProgressHUD hideAllHUDsForView:self.collectionView animated:YES];
            UIAlertView *alter = [[UIAlertView alloc]initWithTitle:@"提示" message:@"上传成功!" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [alter show];
            
            
            
            //发起通知告知前一个页面进行从新获取网络信息,进行页面刷新
            
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"muban" object:nil];
            
            [self.navigationController popViewControllerAnimated:YES];
        }
        else
        {
            [MBProgressHUD hideAllHUDsForView:self.collectionView animated:YES];
            NSString *str = [NSString stringWithFormat:@"%@",responseObject[@"result_msg"]];
            [self.view makeToast:str];
      
        }
    
        
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [MBProgressHUD hideAllHUDsForView:self.collectionView animated:YES];
        
        [self.view makeToast:@"连接服务器失败!"];
        
    }];
    

}



-(void)sendAPI
{
    NSString *urlStr = [NSString stringWithFormat:@"%@/product_template",SERVER_ADDRESS2];
    NSDictionary *params = @{@"wTel" : self.dataHandler.phone , @"uToken" : self.dataHandler.uToken};
    [MBProgressHUD showHUDAddedTo:self.collectionView animated:YES];
    [self.manager POST:urlStr parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
        
        [self response:responseObject];
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    [MBProgressHUD hideAllHUDsForView:self.collectionView animated:YES];
    [self.view makeToast:@"请检查网络!"];
    }];
    
}



-(void)response:(id)responseObject
{
    if ([responseObject[@"error_flag"]intValue] == 0) {
        
        if (![responseObject[@"data"] isKindOfClass:[NSDictionary class]])
        {
            [MBProgressHUD hideAllHUDsForView:self.collectionView animated:YES];
            [self.view makeToast:@"获取服务器数据失败!"];
            return ;
        }
        else
        {
            NSArray *array = responseObject[@"data"][@"product_template"];
            self.list = [NSMutableArray arrayWithArray:array];
            
            
        }
        self.boolArray = [[NSMutableArray alloc]initWithCapacity:0];
        
        for (int i = 0; i < self.list.count ; i++)
        {
            [self.boolArray addObject:@"NO"];
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            
            [self.collectionView reloadData];
            
            
        });
        
        [MBProgressHUD hideAllHUDsForView:self.collectionView animated:YES];
    }
    else
    {
      
        [MBProgressHUD hideAllHUDsForView:self.collectionView animated:YES];
        NSString *str = [NSString stringWithFormat:@"%@",responseObject[@"result_msg"]];
        [self.view makeToast:str];
    }
}


-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{

    return 1;

}



-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{

    return self.list.count;

}


-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    Templet2Cell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Templet2Cell" forIndexPath:indexPath];
    NSDictionary *dict = [self.list objectAtIndex:indexPath.row];
    [cell sizeToFit];
    [cell loadCell:dict];
    
    
    if ([self.boolArray[indexPath.row] isEqualToString:@"YES"]) {
        
        cell.btnImage.image = [UIImage imageNamed:@"gou2"];
    }
    else
    {
    
        cell.btnImage.image = [UIImage imageNamed:@"gou1"];
    
    }
    
    return cell;
 
}


//定义每个Section 的 margin
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(3,3,3,3);//分别为上、左、下、右
}



//定义每个UICollectionViewCell 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    return CGSizeMake(ViewWidth/3 - 4, ViewWidth/3 + 50);
    
}


//每个item的行间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{

    return 2;

}

//设置item 的列间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section;
{
    return 2;
    
}

- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    return YES;
}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    
    NSString *str = self.boolArray[indexPath.row];
    if ([str isEqualToString:@"YES"]) {
        
        
        [self.boolArray replaceObjectAtIndex:indexPath.row withObject:@"NO"];

        
    }
    else
    {
    
        [self.boolArray replaceObjectAtIndex:indexPath.row withObject:@"YES"];
    
    }
    [self.collectionView reloadData];
    
    
    
    
}


@end
